const reser = require("../dao/reserveationList_wxq");
const db = require("../DBcofig/DBConnection");
const limit = 10;
// const jsonwebtoken = require("jsonwebtoken");
// const key = "miyao";
//时间处理函数
function forData(num) {
  const now = new Date();
  const nowTime = now.getTime();
  const day = now.getDay();
  const oneDayTime = 24 * 60 * 60 * 1000;

  // 本周一时间戳
  const MondayTime = nowTime - (day - 1) * oneDayTime + num * oneDayTime;

  // 本周日时间戳
  const SundayTime = nowTime + (7 - day) * oneDayTime + num * oneDayTime;

  // 格式化时间
  const monday = new Date(MondayTime);
  const sunday = new Date(SundayTime);
  // date.format('')可以将标准时间格式转换成 年-月-日，其中date需为标准时间格式

  let year = monday.getFullYear(); //年
  let month = (monday.getMonth() + 1).toString().padStart(2, "0"); //月
  let dayos = monday.getDate().toString().padStart(2, "0"); //日;

  let year1 = sunday.getFullYear(); //年
  let month1 = (sunday.getMonth() + 1).toString().padStart(2, "0"); //月
  let dayos1 = sunday.getDate().toString().padStart(2, "0"); //日;
  let start = year + "-" + month + "-" + dayos;
  let end = year1 + "-" + month1 + "-" + dayos1;

  return { start, end };
}

module.exports = {
  //患者预约挂号查询
  async setreserveation(req, res) {
    let { page, search, radio, startDate, endDate, one_id, two_id } = req.query;
    console.log(page, search, radio, startDate, endDate, one_id, two_id);
    let sql =
      "select * from reservation ,patients_with_wxq,doctor,job_title,attendance_card,department_one,department_two where reservation.patients_id=patients_with_wxq.patients_id and reservation.doctor_id=doctor.dt_id and doctor.rank_id=job_title.jt_id and patients_with_wxq.card_id=attendance_card.card_id and doctor.one_id=department_one.department_one_id and doctor.two_id=department_two.department_two_id ";
    let sqlo =
      "select count(*) as count from reservation ,patients_with_wxq,doctor,job_title,attendance_card,department_one,department_two where reservation.patients_id=patients_with_wxq.patients_id and reservation.doctor_id=doctor.dt_id and doctor.rank_id=job_title.jt_id and patients_with_wxq.card_id=attendance_card.card_id and doctor.one_id=department_one.department_one_id and doctor.two_id=department_two.department_two_id ";
    page = parseInt(page);
    let arr = [];
    let start = (page - 1) * limit;
    if (search != undefined) {
      sql += ` and patients_name like ?`;
      sqlo += ` and patients_name like ?`;
      arr.push(search + "%");
    }
    if (radio != undefined && radio != 3) {
      sql += ` and rt_status=?`;
      sqlo += ` and rt_status=?`;
      arr.push(parseInt(radio));
    }
    if (startDate != undefined && endDate != undefined) {
      sql += ` and startDate >=?  and startDate <?`;
      sqlo += ` and startDate >=?  and startDate <?`;
      arr.push(startDate, endDate);
    }
    if (one_id != undefined && two_id != undefined) {
      sql += ` and one_id=? and two_id=?`;
      sqlo += ` and one_id=? and two_id=?`;
      arr.push(parseInt(one_id), parseInt(two_id));
    }
    let num = await reser.setserveation(res, sqlo, arr);
    let count = num[0].count;
    sql += ` order by rt_status limit ?,?`;
    arr.push(start, limit);

    let data = await reser.setserveation(res, sql, arr);
    res.send({
      code: 200,
      msg: "查询成功",
      data,
      count,
    });
  },
  //修改就诊状态
  async amendServeation(req, res) {
    let { status, id } = req.body;
    console.log(req.body, 123);

    let sql = " UPDATE reservation SET rt_status=? WHERE rt_id=?";
    let arr = [status, id];

    let data = await reser.chageData(res, sql, arr);
    console.log(data);

    res.send(data);
  },
  //科室查询
  async setDesk(req, res) {
    let sql =
      "select * from department_one,department_two where department_two.department_one_id=department_one.department_one_id";

    let data = await reser.setserveation(res, sql, []);

    res.send({
      code: 200,
      msg: "查询成功",
      data,
    });
  },
  //查询所有医生排班
  async setScheduling(req, res) {
    let { date, page, one_id, two_id, search } = req.query;
    // let sql =
    //   "select * from scheduls AS S,doctor AS D,job_title AS J,department_one AS ONE,department_two AS TWO where S.sched_id=D.dt_id and D.rank_id=J.jt_id and D.one_id=ONE.department_one_id and D.two_id=TWO.department_two_id ";
    let sqlo = "select count(*) from doctor where 1=1 ";
    let sqlp =
      "select * from doctor AS D,job_title AS J,department_one AS ONE,department_two AS TWO where D.rank_id=J.jt_id and D.one_id=ONE.department_one_id and D.two_id=TWO.department_two_id ";

    let sqle = "select * from scheduls where doctor_id=? ";

    let arr = [];
    page = parseInt(page);
    let start = (page - 1) * limit;

    if (search != undefined) {
      sqlo += ` and name like ?`;
      sqlp += ` and name like ?`;
      arr.push(search + "%");
    }
    if (date != undefined) {
      date = parseInt(date);
      switch (date) {
        case 0:
          // sqle += ` and YEARWEEK(date_format(sched_date,'%Y-%m-%d')) = YEARWEEK(now())-1`;
          sqle += ` and sched_date>="${forData(-7).start}" and sched_date<="${forData(-7).end
            }"`;

          break;
        case 1:
          // sqle += ` and YEARWEEK(date_format(sched_date,'%Y-%m-%d')) = YEARWEEK(now())`;
          sqle += ` and sched_date>="${forData(0).start}" and sched_date<="${forData(0).end
            }"`;

          break;
        case 2:
          // sqle += ` and YEARWEEK(date_format(sched_date,'%Y-%m-%d')) = YEARWEEK(now())+1`;
          sqle += ` and sched_date>="${forData(7).start}" and sched_date<="${forData(7).end
            }"`;

          break;
      }
    }
    if (one_id != undefined && two_id != undefined) {
      sqlo += ` and one_id=? and two_id=?`;
      sqlp += ` and one_id=? and two_id=?`;
      arr.push(parseInt(one_id), parseInt(two_id));
    }

    let nums = await reser.setserveation(res, sqlo, arr);
    let count = nums[0]["count(*)"];

    arr.push(start, limit);
    sqlp += ` order by dt_id limit ?,?`;
    let doctor = await reser.setserveation(res, sqlp, arr);

    let whereArr = [];
    doctor.forEach((element) => {
      let arr1 = [...arr];
      let id = element.dt_id;

      arr1.unshift(id);
      whereArr.push(arr1);
    });

    for (let i = 0; i < whereArr.length; i++) {
      let has = await reser.setserveation(res, sqle, whereArr[i]);
      doctor.forEach((ele) => {
        if (ele.dt_id == whereArr[i][0]) {
          ele.has = has;
        }
      });
    }

    // let data = await reser.setserveation(res, sql, arr);
    res.send({
      code: 200,
      msg: "查询成功",
      data: doctor,
      count,
    });
  },
  //查询医生个人排班
  async setDocterDate(req, res) {
    let { date, id } = req.query;
    let arr = [];
    id = parseInt(id);
    let sqle = "select * from scheduls where doctor_id=? ";

    arr.push(id);

    if (date != undefined) {
      date = parseInt(date);
      switch (date) {
        case 5:
          sqle += ` and DATE_FORMAT(sched_date,'%Y%m') = DATE_FORMAT(CURDATE() , '%Y%m')`;
          break;
        case 4:
          sqle += ` and PERIOD_DIFF( date_format( now( ) , '%Y%m' ) , date_format( sched_date, '%Y%m' ) ) =1`;

          break;
        case 6:
          sqle += ` and date_format(sched_date,'%Y-%m-%d') = date_format(DATE_SUB(curdate(), INTERVAL 1 MONTH), '%Y-%m')`;
          break;
      }
    }
    console.log(arr, sqle);
    let data = await reser.setserveation(res, sqle, arr);
    res.send({
      code: 200,
      msg: "查询成功",
      data,
    });
  },
  //修改排班
  async amendWork(req, res) {
    let { date, id, am, pm } = req.body;
    let arr = [];

    let sql =
      " UPDATE scheduls SET am=?,pm=? WHERE doctor_id=? and sched_date=?";
    arr.push(am, pm, id, date);
    console.log(req.body, arr, sql);

    let data = await reser.chageData(res, sql, arr);

    res.send(data);
  },
  //新增排班
  async addWork(req, res) {
    let { date, id, am, pm } = req.body;
    let arr = [];
    let sql = " insert into scheduls values(null,?,?,?,?,null,null,null,null)";
    arr.push(id, am, pm, date);
    console.log(req.body, arr, sql);
    let data = await reser.chageData(res, sql, arr);

    res.send(data);
  },

  //账号登录

  async login(req, res) {
    let { userName, passWord } = req.body;
    let sql = "select * from user_wxq where user_name=? and password=?";
    let arr = [userName, passWord];

    let data = await reser.setserveation(res, sql, arr);
    if (data.length > 0) {
      // let token = jsonwebtoken.sign(
      //   {
      //     user: data[0].user_name,
      //   },
      //   key,
      //   {
      //     expiresIn: "6000s",
      //   }
      // );
      // res.setHeader("token", token);
      res.send({
        code: 200,
        userName: data[0].user_name,
        userId: data[0].user_id,
        msg: "登录成功",
      });
    } else {
      res.send(data);
    }
  },
};
